//
//  PublishNoticeViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/5/18.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "PublishNoticeViewController.h"
#import <TPKeyboardAvoidingTableView.h>
#import "CommonResponse.h"
#import "GTMBase64.h"
#import <MBProgressHUD.h>
#import "UITapLabel.h"
#import "CubeAdTextView.h"

#define DEFAULT_IMAGE_WIDTH 2500

@interface PublishNoticeViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate, UITextViewDelegate> {
    MBProgressHUD *HUD;
}

@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UIImage *image;
@property (nonatomic,strong) UITextField *titleView;
@property (nonatomic,strong) CubeAdTextView *contentView;
@property (nonatomic,strong) UITapLabel *closeBtn;
@property (nonatomic,copy) NSString *guidid;


@end

@implementation PublishNoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    //[self setupViews];
    [self loadData];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setupViews];
}

#pragma mark - 初始化视图
- (void)setupViews{
    if (self.publishType == KKPublish_Notice) {
        self.title = @"发布公告";
    }
    else {
        self.title = @"发表意见";
    }
    self.view.backgroundColor = [UIColor whiteColor];
    
    //适配iOS7uinavigationbar遮挡tableView的问题
    if(IS_IOS7)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    //自定义返回按钮
    UIBarButtonItem *backBtn;
    if (self.publishType == KKPublish_Notice) {
        backBtn = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStyleDone target:self action:@selector(onPublish)];
    }
    else {
        backBtn = [[UIBarButtonItem alloc] initWithTitle:@"发表" style:UIBarButtonItemStyleDone target:self action:@selector(onPublish)];
    }
    self.navigationItem.rightBarButtonItem = backBtn;

    //列表
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (UIImage *)croppedImage:(UIImage *)image

{
    if (image)
    {
        CGRect rectMAX = CGRectMake(0, 0, 128, 128);
        
        CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rectMAX);
        
        UIGraphicsBeginImageContext(rectMAX.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextDrawImage(context, rectMAX, subImageRef);
        UIImage *viewImage = [UIImage imageWithCGImage:subImageRef];
        UIGraphicsEndImageContext();
        CGImageRelease(subImageRef);
        return viewImage;
    }
    
    return nil;
    
}

#pragma mark - 事件响应
- (void)onPublish {
    if (self.guidid != nil) {
        if (self.image != nil) {
            [self updateImage];
        }
        [Tools showMessageCenter:@"请选择要上传的图片"];
        return;
    }
    
    if (self.titleView.text == nil || self.titleView.text.length == 0) {
        [Tools showMessageCenter:@"请输入标题"];
        return;
    }
    if (self.contentView.text == nil || self.contentView.text.length == 0) {
        [Tools showMessageCenter:@"请输入内容"];
        return;
    }
    
    NSString *title = [self.titleView.text base64Encoder];
    NSString *content = [self.contentView.text base64Encoder];
    NSString *url;
    
    if (self.publishType == KKPublish_Notice) {
        url = [NSString stringWithFormat:@"%@2.0/postmanager.svc/?token=%@", HTTP_HOST, [[AccountManager manager]token]];
    }
    else {
        url = [NSString stringWithFormat:@"%@2.0/suggestionmanager.svc/?token=%@", HTTP_HOST, [[AccountManager manager]token]];
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:title forKey:@"title"];
    [param setObject:content forKey:@"content"];
    
    [Tools printJsonStr:param];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"发布中...";
    
    [HttpClient postWithUrl:url paramDic:param resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        if (self.image != nil) {
            if (self.publishType == KKPublish_Notice) {
                self.guidid = obj.sendPostResult;
            }
            else {
                self.guidid = obj.sendSuggestionResult;
            }
            [HUD setHidden:YES];
            if (self.image != nil) {
                [self updateImage];
            }
            else {
                [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"发布成功！" cancelButtonTitle:@"确定" otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }
        }
        else {
            [HUD setHidden:YES];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        [Tools showMessageCenter:@"提交失败,请重试！"];
        CMLog(@"发布失败：%@", error);
    }];
}

- (void)updateImage {
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"图片上传中";
    //开始上传图片
    
    //对图片进行压缩处理
    if (self.image.size.width > DEFAULT_IMAGE_WIDTH) {
        CGSize size;
        size.width = DEFAULT_IMAGE_WIDTH;
        size.height = self.image.size.height * DEFAULT_IMAGE_WIDTH/self.image.size.width;
        self.image = [self imageWithImage:self.image scaledToSize:size];
    }
    
    NSData* imageData;
    NSString *mimeType;
    //判断图片是不是png格式的文件
    if (UIImagePNGRepresentation(self.image)) {
        //返回为png图像。
        imageData = UIImagePNGRepresentation(self.image);
        mimeType = @"image/png";
    }else if (UIImageJPEGRepresentation(self.image, 1.0)) {
        //返回为JPEG图像。
        imageData = UIImageJPEGRepresentation(self.image, 1.0);
        mimeType = @"image/jpeg";
    }
    else {
        [Tools showMessageCenter:@"图片格式不支持，请重试"];
        return;
    }
    
//    CMLog(@"图片数据:%@", imageData);
    
//    imageData = [GTMBase64 encodeData:imageData];
    //            NSString *base64String = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding];
    
    NSString *picUrl;
    if (self.publishType == KKPublish_Notice) {
        picUrl = [NSString stringWithFormat:@"%@2.0/postmanager.svc/sendpic?token=%@&id=%@", HTTP_HOST, [[AccountManager manager]token], self.guidid];
    }
    else {
        picUrl = [NSString stringWithFormat:@"%@2.0/suggestionmanager.svc/sendpic?token=%@&id=%@", HTTP_HOST, [[AccountManager manager]token], self.guidid];
    }
    
    [HttpClient postUploadImage:picUrl andMimeType:mimeType andData:imageData resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        [HUD setHidden:YES];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        [Tools showMessageCenter:@"图片上传失败,请重试！"];
        
        for (NSString *key in error.userInfo) {
            CMLog(@"key: %@ value: %@", key, error.userInfo[key]);
        }
//        CMLog(@"图片上传失败：%@", [error.userInfo get]);
    }];
}

- (void)pickerFromPhotoLib
{
    UIImagePickerController *imagepicker = [[UIImagePickerController alloc] init];
    imagepicker.delegate = self;
    imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagepicker.allowsEditing = NO;
    [self presentViewController:imagepicker animated:YES completion:^{
        
    }];
}

#pragma mark - 图片选择器代理

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    // 判断，图片是否允许修改
    if ([picker allowsEditing]){
        //获取用户编辑之后的图像
        self.image = [info objectForKey:UIImagePickerControllerEditedImage];
    } else {
        // 照片的元数据参数
        self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    self.closeBtn.hidden = NO;
    [self.imageView setImage:self.image];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//完成选取

// 取消选取
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

#pragma mark - 加载数据
/**
 *  初始化数据
 */
- (void)initData {
    self.guidid = nil;
}

/**
 *  加载视图所有的数据
 */
- (void)loadData {
    
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"produceCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"produceCell"];
    }
    cell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
    cell.textLabel.font = [UIFont systemFontOfSize:kListTitleFontSize];
    
    if (indexPath.section == 1) {
        cell.textLabel.text = @"选择图片";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.textLabel.text = @"内容";
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        [self pickerFromPhotoLib];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return kScreen_Width;
    }
    else {
        return 6*DEFAULT_SECTION_HEIGHT;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0)];
    footerView.backgroundColor = [UIColor whiteColor];
    if (section == 1) {
        if (self.imageView == nil) {
            self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(CELL_PADDING_LEFT, 0, kScreen_Width - 2*CELL_PADDING_LEFT, kScreen_Width - 2*CELL_PADDING_LEFT)];
        }
        
        if (self.closeBtn == nil) {
            self.closeBtn = [[UITapLabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.imageView.frame) - 60, 0, 60, 60)];
            self.closeBtn.backgroundColor = [UIColor clearColor];
            self.closeBtn.textAlignment = NSTextAlignmentCenter;
            self.closeBtn.text = @"X";
            self.closeBtn.font = [UIFont systemFontOfSize:32];
            self.closeBtn.textColor = CM_NAVIGATION_RED_COLOR;
            __block PublishNoticeViewController *tmp = self;
            [self.closeBtn addTargetsBlock:^(id obj) {
                if (tmp.image != nil) {
                    tmp.image = nil;
                    tmp.closeBtn.hidden = YES;
                    [tmp.imageView setImage:nil];
                    //[tmp.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
                }
            }];
        }
        if (self.image != nil) {
            self.closeBtn.hidden = NO;
        }
        else {
            self.closeBtn.hidden = YES;
        }
        
        [footerView addSubview:self.imageView];
        [footerView addSubview:self.closeBtn];
    } else {
        if (self.contentView == nil) {
            self.contentView = [[CubeAdTextView alloc]initWithFrame:CGRectMake(CELL_PADDING_LEFT, 0, kScreen_Width - CELL_PADDING_LEFT - CELL_PADDING_RIGHT, 3*DEFAULT_SECTION_HEIGHT)];
            self.contentView.backgroundColor = [UIColor whiteColor]; // 设置背景色
            self.contentView.alpha = 1.0; // 设置透明度
            self.contentView.placehoder = @"请输入内容";
            self.contentView.placehoderColor = CM_PLACEHOLDER_TEXT_COLOR;
            self.contentView.textAlignment = NSTextAlignmentLeft; // 设置字体对其方式
            self.contentView.font = [UIFont systemFontOfSize:kListTitleFontSize]; // 设置字体大小
            self.contentView.textColor = CM_TABLE_DETAIL_COLOR; // 设置文字颜色
            [self.contentView setEditable:YES]; // 设置时候可以编辑
            self.contentView.dataDetectorTypes = UIDataDetectorTypeAll; // 显示数据类型的连接模式（如电话号码、网址、地址等）
            self.contentView.keyboardType = UIKeyboardTypeDefault; // 设置弹出键盘的类型
            self.contentView.returnKeyType = UIReturnKeyDefault; // 设置键盘上returen键的类型
            self.contentView.scrollEnabled = YES; // 当文字宽度超过UITextView的宽度时，是否允许滑动
        }
        [footerView addSubview:self.contentView];
    }
    
    
    return footerView;
}

/**
 *  对图片尺寸进行压缩
 *
 *  @param image   <#image description#>
 *  @param newSize <#newSize description#>
 *
 *  @return <#return value description#>
 */
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (void)titleEditingEnd {
    
}


- (void)textViewDidEndEditing:(UITextView *)textView {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
